/**
 * 
 */
package org.adempiere.apps.graph;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;

import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.AutoCompletion;
import org.compiere.grid.ed.VComboBox;
import org.compiere.model.MBSCCard;
import org.compiere.model.MBSCCardLine;
import org.compiere.model.MParameter;
import org.compiere.model.MPeriod;
import org.compiere.model.MRole;
import org.compiere.model.X_BSC_CardLine;
import org.compiere.swing.CButton;
import org.compiere.swing.CComboBox;
import org.compiere.swing.CPanel;
import org.compiere.swing.CScrollPane;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;

/**
 * @author Y.Ibrayev
 *
 */
public class BSCViewCardLine2 extends CPanel implements FormPanel, ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4566997842038308824L;
	private static CLogger log = CLogger.getCLogger (BSCView.class);
	private int m_WindowNo = 0;
	private FormFrame m_frame;
	private ConfirmPanel confirmPanel = new ConfirmPanel();
	private CPanel mainPanel = new CPanel();
	private GridBagLayout parameterLayout = new GridBagLayout();
	private CPanel loadPanel = new CPanel(new FlowLayout(FlowLayout.LEADING));
	private VComboBox cbDepartaments = new VComboBox();
	private VComboBox cbPeriod = new VComboBox();
	private CButton bBack = new CButton();
	private int dep = 0;
	private int period = 0;

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals(ConfirmPanel.A_OK))
			dispose();
		else if (e.getSource() == cbDepartaments && cbDepartaments.getSelectedItem() != null) {
			KeyNamePair knp = (KeyNamePair) cbDepartaments.getSelectedItem();
			dep = knp.getKey();
//			period = new MPeriod(Env.getCtx(), period_ID, null);
//			setCard(BSC_Card_ID);
//			KeyNamePair[] pp = getBSCCardLine(BSC_Card_ID);			
//			cbCardLine.setModel(new DefaultComboBoxModel<KeyNamePair>(pp));
//			System.out.println("perform ac dep: " + dep);
			load(dep, period);
			
		}
		else if (e.getSource() == cbPeriod && cbPeriod.getSelectedItem() != null) {
			KeyNamePair knp = (KeyNamePair) cbPeriod.getSelectedItem();
			period = knp.getKey(); 
//			
//			String sql = 
//				"select c_period_id, name from adempiere.c_period	\n"	+
//				"where c_year_id = " + period;
//			
//			KeyNamePair[] pp = DB.getKeyNamePairs(sql, true);
//			cbMonths.setModel(new DefaultComboBoxModel<KeyNamePair>(pp));
//			load(BSC_Card_ID,BSC_CardLine_ID);
			
//			System.out.println("perform ac per: " + period);
			load(dep, period);
			
			
		} else if (e.getSource() instanceof BSCCardLineIndicator) {
//			load(dep, year, month);
//			BSCCardLineIndicator ind = (BSCCardLineIndicator) e.getSource();
//			MBSCCardLine _cardLine = ind.getCardLine();
//			setCardLine((_cardLine != null ? _cardLine.getBSC_CardLine_ID(): 0));
//			
//			KeyNamePair[] pp = getBSCCardLine(cardLine.getBSC_Card_ID());			
//			cbCardLine.setModel(new DefaultComboBoxModel<KeyNamePair>(pp));
//			if (_cardLine != null && cardLine == null)
//				setCardLine((_cardLine != null ? _cardLine.getBSC_CardLine_ID(): 0));
//			cbCardLine.setValue(cardLine.getBSC_CardLine_ID());
//			
//			load(cardLine.getBSC_Card_ID(),cardLine.getBSC_CardLine_ID());
//		} else if (e.getSource() == bBack) {
//			goBack();
//			load((card == null ? 0 : card.getBSC_Card_ID()), (cardLine == null ? 0 : cardLine.getBSC_CardLine_ID()));
		}
	}

	/**
	 * 
	 */
//	private void goBack() {
//		if(cardLine != null) {
//			MBSCCardLine prevCardLine = cardLine.getLink();
//			int prevBSC_CardLine_ID = (prevCardLine != null ? prevCardLine.getBSC_CardLine_ID() : 0);
//			setCardLine(prevBSC_CardLine_ID);
//		} else {
//			//TODO
//		}
//	}

	/* (non-Javadoc)
	 * @see org.compiere.apps.form.FormPanel#init(int, org.compiere.apps.form.FormFrame)
	 */
	@Override
	public void init(int WindowNo, FormFrame frame) {
		log.fine("BSCView");
		m_WindowNo = WindowNo;
		m_frame = frame;
//		card = new MBSCCard(Env.getCtx(), 1000053, null);
//		prepare();
		
		try {
			initLoadPanel();
			initMainPanel();
			confirmPanel.addActionListener(this);
			
			m_frame.getContentPane().add(loadPanel, BorderLayout.NORTH);
			m_frame.getContentPane().add(confirmPanel, BorderLayout.SOUTH);
			CScrollPane scroll =  new CScrollPane(mainPanel);
			m_frame.getContentPane().add(scroll, BorderLayout.CENTER);
			m_frame.setMaximize(true);
			
		} catch(Exception e) {
			log.log(Level.SEVERE,"BSCView: ",e);
		}
	}

	/* (non-Javadoc)
	 * @see org.compiere.apps.form.FormPanel#dispose()
	 */
	@Override
	public void dispose() {
		if (m_frame != null)
			m_frame.dispose();
		m_frame = null;
		removeAll();
	}

	
	private void initLoadPanel() {
//		loadPanel.add(initBBack());
		loadPanel.add(initDepartaments());
		loadPanel.add(initPeriod());
//		loadPanel.add(initMonths());
	}
	
	private void initMainPanel() {
		mainPanel.setLayout(new GridBagLayout());
		load(dep,period);
	}

//	private CButton initBBack() {
//		bBack = new CButton("<<");
//		bBack.addActionListener(this);
//		return bBack;
//	}
	
	private CComboBox initDepartaments() {
		String sql = 
				"select hr_department_id, name	\n" +
				"from adempiere.hr_department where hr_department_id in (2000010,2000017,2000020,2000001,2000006)	\n"	+
				"order by hr_department_id";
				
		KeyNamePair[] pp = DB.getKeyNamePairs(sql, true);
		cbDepartaments = new VComboBox(pp);
		AutoCompletion.enable(cbDepartaments);
		cbDepartaments.addActionListener(this); 
		return cbDepartaments;

	}
	
	private CComboBox initPeriod() {
		String sql = 
//			"	select c_period_id, name from adempiere.c_period \n"	+
//			"	order c_period_id \n"	;
				
				 "select p.c_period_id, p.name	\n"	+  
				 "from adempiere.bsc_card c	\n"	+
				 "inner join adempiere.c_period p on p.c_period_id = c.c_period_id	\n"	+
				 "group by 1	\n"	+
				 "order by 1	\n"	;
				 
		KeyNamePair[] pp = DB.getKeyNamePairs(sql, true);		
		cbPeriod = new VComboBox(pp);
		AutoCompletion.enable(cbPeriod);
		cbPeriod.addActionListener(this); 
		return cbPeriod;
	}
	
//	private CComboBox initMonths() {
//				
//		KeyNamePair[] pp = new KeyNamePair[1];	
//		cbMonths = new VComboBox(pp);
//		AutoCompletion.enable(cbMonths);
//		cbMonths.addActionListener(this); 
//		return cbMonths;
//	}
	
	public void load(int idep, int iperiod) {
		
		mainPanel.removeAll();
		
		if(idep != 0 && iperiod != 0 )
		viewCard(idep, iperiod);

		mainPanel.validate();
		mainPanel.repaint();
		mainPanel.updateUI();
		
		return ;
	}
	
	private void viewCard(int idep, int iperiod) {
		GridBagConstraints gbc = new GridBagConstraints();
		
		String deps = "";
//		System.out.println(idep);
		switch(idep){
//				1 itk
			case 2000010:
				deps = "2000015, 1000001, 1000002, 1000003";
				break;
//			2	gos sektor
			case 2000017:
				deps = "1000000, 2000018, 2000013";
				break;
//			3	'conomic and fiv
			case 2000020:
				deps = "2000024, 2000021, 2000023, 2000022";
				break;
//			4	boss
			case 2000001:
				deps = "2000025, 2000002, 2000003, 2000005, 2000004";
				break;
//			5	ruk apparata
			case 2000006:
				deps = "2000007, 2000009, 2000008";
				break;
		}
		
		
		String sql = 	
//				"select dep.name, sum(card.valuenumber)	\n"	+
//				"from adempiere.bsc_card card	\n"	+
//				"inner join adempiere.hr_employee employee on employee.c_bpartner_id = card.c_bpartner_id	\n"	+
//				"inner join adempiere.hr_department dep on dep.hr_department_id = employee.hr_department_id	\n"	+
//				"where employee.hr_department_id in ("+deps+")	\n"	+
//				"and card.c_period_id = " + iperiod + "\n" +
//				"group by 1	\n"	+
//				"order by 1	\n"	;
				"select	\n"	+ 
				"dep.name, coalesce(sum(card.valuenumber),0) summ, count(employee.c_bpartner_id) countt	\n"	+
				"from adempiere.hr_employee employee \n"	+
				"inner join adempiere.hr_department dep on dep.hr_department_id = employee.hr_department_id\n"	+
				"left join adempiere.bsc_card card on card.c_bpartner_id = employee.c_bpartner_id and card.c_period_id = "+iperiod+"	\n"	+
				"where employee.hr_department_id in ("+ deps +")\n"	+
				"group by 1\n"	+
				"order by 1\n"	;

		
//		System.out.println(sql);
		
		List<MBSCCard> list = new ArrayList<MBSCCard>(); 
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		try {
			pstmt = DB.prepareStatement(sql,null);
			rs = pstmt.executeQuery();
			int i = 0;
			while (rs.next()) {
				
				gbc.fill = GridBagConstraints.HORIZONTAL;
				gbc.gridx = i++;
				gbc.gridy = 0;
				
				BigDecimal bd = rs.getBigDecimal(2);
				String name = rs.getString(1);
				int count = rs.getInt(3);
				
				double b = bd.doubleValue();
//				System.out.println("bd: " + bd + ", count: " + count + ", b: " + b);
				
				if(b != 0)
					b = b / count;
								
//				if(bd.compareTo(Env.ZERO) == 1)
//					bd = bd.divide(new BigDecimal(count));
				
				addCardIndicator(gbc, name, new BigDecimal(b));
			}
		} catch (SQLException e) {
			log.log(Level.SEVERE, "product", e);
		} finally {
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}	
//		
//		
//		for(int i=0; i<list.size(); i++){
//			setCard(list.get(i).get_ID());
////			System.out.println(list.get(i).get_ID());
//			gbc.fill = GridBagConstraints.HORIZONTAL;
//			gbc.gridx = i;
//			gbc.gridy = 0;
//			
//			addCardIndicator(gbc);
//		}

		
//		gbc.fill = GridBagConstraints.HORIZONTAL;
//		gbc.gridx = 0;
//		gbc.gridy = 0;
//		
//		BigDecimal bd = new BigDecimal(100);
//		
//		addCardIndicator(gbc, "alm", bd);
		
		mainPanel.validate();
		mainPanel.repaint();
		mainPanel.updateUI();
	}
	
	
	
	/**
	 * @param cardLines
	 * @param gbc
	 */
//	private void addCardLines(MBSCCardLine[] cardLines, GridBagConstraints gbc) {
//		BSCLine tempLine = null;
//		int i = 1;
//		for(MBSCCardLine line: cardLines) {
//			gbc = new GridBagConstraints();
//			
//			gbc.fill = GridBagConstraints.HORIZONTAL;
//			gbc.gridx = 0;
//			gbc.gridy = i;
//			tempLine = addTempLine(gbc);
//			
//			gbc = new GridBagConstraints();
//			
//			gbc.fill = GridBagConstraints.HORIZONTAL;
//			gbc.gridx = 1;
//			gbc.gridy = i++;
//			addCardLineIndicator(line,gbc);
//		}
//		
//		if (tempLine != null) {
//			tempLine.setEnd(true);
//			tempLine.repaint();
//		}
//		
//	}
//
//	/**
//	 * @param line
//	 * @param gbc
//	 */
//	private void addCardLineIndicator(MBSCCardLine line, GridBagConstraints gbc) {
//		if (line==null) {
//			return;
//		}
//		BSCCardLineIndicator indicator = new BSCCardLineIndicator(line);
//		indicator.addActionListener(this);
//		mainPanel.add(indicator,gbc);
//		return;
//	}
//
//	/**
//	 * @param gbc
//	 * @return
//	 */
//	private BSCLine addTempLine(GridBagConstraints gbc) {
//		BSCLine tempLine = new BSCLine();
//		mainPanel.add(tempLine,gbc);
//		return tempLine;
//	}

	/**
	 * @param gbc
	 */
	private void addTempPanel(GridBagConstraints gbc) {
		JPanel temp = new JPanel();
		temp.setPreferredSize(BSCIndicator.paneldimension);
		mainPanel.add(temp,gbc);
	}

//	private void viewCardLine() {
//		GridBagConstraints gbc = new GridBagConstraints();
//		
//		gbc.fill = GridBagConstraints.HORIZONTAL;
//		gbc.gridx = 0;
//		gbc.gridy = 0;
//		
//		addCardLineIndicator(cardLine,gbc);
//		
//		gbc = new GridBagConstraints();
//		
//		gbc.fill = GridBagConstraints.HORIZONTAL;
//		gbc.gridx = 1;
//		gbc.gridy = 0;
//		
//		addTempPanel(gbc);
//		
//		MBSCCardLine[] cardLines = cardLine.getLinkLines();
//		addCardLines(cardLines, gbc);
//		
//		mainPanel.validate();
//		mainPanel.repaint();
//		mainPanel.updateUI();
//	}
	
	private void addCardIndicator(GridBagConstraints gr, String name, BigDecimal value ) {
		BSCCardIndicator2 indicator = new BSCCardIndicator2(name, value);
		indicator.addActionListener(this);
		mainPanel.add(indicator,gr);
	}
	
	

}
